package com.ccom.core.common.util;

import org.apache.commons.lang3.math.NumberUtils;

import java.util.ArrayList;
import java.util.List;

public class JarVersionUtils {
    private JarVersionUtils() {
    }

    private static final String MF = "META-INF/MANIFEST.MF";
    private static final String VERSION_PREFIX = "Implementation-Version: ";
    private static final String BUNDLE_VERSION_PREFIX = "Bundle-Version: ";
    private static final String SPLIT = "-";

    /**
     * 获得指定class所在jar包的版本号
     *
     * @param clazz
     * @return
     */
    public static String getJarVersion(Class clazz) {
        Package pkg = clazz.getPackage();
        return (pkg != null ? pkg.getImplementationVersion() : null);
    }

    /**
     * 判断jar的当前版本号是否大于基准版本号
     * ,版本号格式必须为下面几个之一(x、y、z表示数字，*表示任意字符串)：
     * <br/>
     * x.y.z.* (也可以是x.y.*等任意多个数字和.的组合格式)
     * <br/>
     * x.y.z-* (也可以是x.y.*等任意多个数字和.的组合格式)
     * <br/>
     * x.y.z (也可以是x.y.*等任意多个数字和.的组合格式)
     *
     * @param currentVersion 当前版本号
     * @param baseVersion    基准版本号
     * @return true/false（当值为false时也有可能是版本号不标准，无法判断）
     */
    public static boolean isJarVersionEqualOrGreaterThan(String currentVersion, String baseVersion) {
        if (StringUtils.isBlank(currentVersion) || StringUtils.isBlank(baseVersion)) {
            return false;
        }

        Integer[] currentVersionArr = normalization(currentVersion);
        if (currentVersionArr == null) {
            return false;
        }
        Integer[] baseVersionArr = normalization(baseVersion);
        if (baseVersionArr == null) {
            return false;
        }

        int minLen = Math.min(currentVersionArr.length, baseVersionArr.length);
        for (int i = 0; i < minLen; i++) {
            if (currentVersionArr[i] > baseVersionArr[i]) {
                return true;
            } else if (currentVersionArr[i] < baseVersionArr[i]) {
                return false;
            }
        }

        if (currentVersionArr.length >= baseVersionArr.length) {
            return true;
        } else {
            return false;
        }
    }

    private static Integer[] normalization(String v) {
        if (v.contains(SPLIT)) {
            v = v.substring(0, v.indexOf('-'));
        }

        String[] vs = StringUtils.split(v, '.');
        List<Integer> vsList = new ArrayList<>();
        for (int i = 0; i < vs.length; i++) {
            String v1 = vs[i];
            if (NumberUtils.isDigits(v1)) {
                vsList.add(Integer.parseInt(v1));
            } else if (i < vs.length - 1) {
                //中间不允许出现非数字
                return null;
            }
        }

        return vsList.toArray(new Integer[vsList.size()]);
    }

}
